<script lang="ts" setup>
import {
  ref,
  reactive,
  provide,
  PropType,
  watch,
  computed,
  watchEffect,
  onMounted
} from 'vue';
import {
  IconSwap,
  IconEdit,
  IconPlus,
  IconDelete
} from '@arco-design/web-vue/es/icon';
import indexAdd from '@/assets/images/index_add.svg';
import { DATEMODE, PERIOD, StaticTime } from '@/constants/indexTree';
import IndexModal from '../components/IndexModal/index.vue';
import IndexCompareModal from '../components/IndexCompareModal/index.vue';
import IndexTreeList from '../components/IndexTreeList/index.vue';
import API from '@/services';
import Bus from '@/utils/emmit';
import {getYearWeek, getQuerterFormatter,getDateOfWeek, showQuerterFormatter} from '@/utils/util';
import _ from 'lodash';
import { Message } from '@arco-design/web-vue';
import TimeSelect from '../components/TimeSelect/index.vue';
import { nanoid } from 'nanoid';
import settingImg from '@/assets/images/setting_img.svg';
import {debounce} from 'lodash'
const props = defineProps({
  metricsConfig: {
    type: Object as PropType<any>
  },
  initCardParam: {
    type: Object as PropType<any>
  },
});
const emit = defineEmits([
  'reviewResultData',
]);
const indexConfig = reactive<any>({
  dateCondition: {
    dateMode: 'BEFORE',
    offset: 1,
    timeUnit: 'DAY',
    fixDate: ''
  },
  target: undefined,
  compareValue: '',
  metricsName: '',
  metricsSetting: {
    statisticalPeriod: {
      type: 'DAY',
      offset: 1,
      timeUnit: 'DAY'
    },
    rela: 'AND',
    numberFormat: 'GE',
    metricsConditions: []
  },
  cardName: '',
  compare: {
    compareName: '',
    compareType: '',
    dateCondition: {
      dateMode: '',
      offset: undefined,
      fixDate: undefined,
      timeUnit: undefined
    }
  },
  metricsId: undefined,
  keys: undefined,
  id: undefined
});
const defaultMetricConfig = _.cloneDeep(indexConfig);
const indexModalRef = ref();
const indexCompareRef = ref();

const styleWidth = ref('w126');
const visibleCompare = ref<boolean>(false);
const dimensionConditionObj = reactive<any>({
  dimensionOption: undefined,
  ifGroupBy: undefined,
  timeframe: ''
});

const handlePopModal = () => {
  indexModalRef.value.popVisible();
};
const handleIndexCompare = (type:String) => {
  if (indexConfig?.compare?.compareName && type === 'add') {
    return
  }
  indexCompareRef.value.openIndexCompare();
  visibleCompare.value = true;
};
const indexPopoverVisible = ref<boolean>(false);

// 切换指标卡
const changeIndexCard = debounce(async(v: any) => {
  
  v.id = nanoid(10);
  Bus.emit('exchangeMetricsCard', v, props.metricsConfig)
  const domDelBtn = document.getElementsByClassName('change-card-content')
  domDelBtn[0].remove()
}, 2000, {
    'leading': true,
    'trailing': false
})


// 统计周期跟默认数据时间粒度保持一致
const getFilterDimension = async (id: any) => {
  try {
    const { code, data } =
      await API.metricsModelRelation.getGetMetricsFilterById({
        id
      });
    if (code === 200) {
      dimensionConditionObj.ifGroupBy = data?.ifGroupBy;
      dimensionConditionObj.dimensionOption = data?.queryFieldList;
      dimensionConditionObj.timeframe = data?.timeframe?.toLocaleUpperCase();
    }
  } catch (error) {}
};
// 统计时间
const timeConfigSuccess = (v: any) => {
  if (dimensionConditionObj.ifGroupBy) {
    indexConfig.metricsSetting = _.cloneDeep(v);
    return;
  }
    if (v.statisticalPeriod.type === 'RECENT') {
      if (indexConfig.dateCondition.timeUnit != StaticTime[v.statisticalPeriod.timeUnit]) {
        indexConfig.dateCondition.timeUnit = StaticTime[v.statisticalPeriod.timeUnit];
        // 是最近状态时且改变时间粒度时，指标配置的默认数据时间就要重置
        indexConfig.dateCondition.fixDate = ''
        indexConfig.dateCondition.offset = 1
        indexConfig.dateCondition.dateMode = 'BEFORE'
        indexConfig.compare.dateCondition.timeUnit = indexConfig.dateCondition.timeUnit
      }
      
    } 
    if (v.statisticalPeriod.type != 'RECENT') {
      if (indexConfig.dateCondition.timeUnit != StaticTime[v.statisticalPeriod.type]) {
        indexConfig.dateCondition.timeUnit = StaticTime[v.statisticalPeriod.type];

        // 不是最近状态时且改变时间粒度时，指标配置的默认数据时间就要重置
        indexConfig.dateCondition.fixDate = ''
        indexConfig.dateCondition.offset = 1
        indexConfig.dateCondition.dateMode = 'BEFORE'
        indexConfig.compare.dateCondition.timeUnit = indexConfig.dateCondition.timeUnit
      }
    }
  indexConfig.metricsSetting = _.cloneDeep(v);
};

// 对比值
const indexCompareOk = (v: any) => {
  indexConfig.compareValue = v.compareName;
  indexConfig.compare = v;
};
// 预览
const metricsPreview = () => {
  if (!indexConfig.dateCondition.dateMode) {
    Message.warning('请选择默认数据时间');
    return;
  }
  if (indexConfig.dateCondition.dateMode === 'BEFORE' && !indexConfig.dateCondition.offset) {
    Message.warning('请选择默认数据时间');
    return;
  }
  if (
    indexConfig.dateCondition.dateMode === 'FIXDATE' &&
    !indexConfig.dateCondition.fixDate
  ) {
    Message.warning('请选择默认数据时间');
    return;
  }
  const reviewResultParams = _.cloneDeep(indexConfig)

  const dateCondition = reviewResultParams.dateCondition
  const compareTimerConfig = reviewResultParams.compare.dateCondition
  // 默认数据时间的配置
  if ( dateCondition.dateMode === 'FIXDATE') {
      if (dateCondition.timeUnit === 'WEEK') {
        dateCondition.fixDate = getYearWeek(new Date(dateCondition.fixDate))
      }
      if (dateCondition.timeUnit === 'QUARTER') {
      dateCondition.fixDate = getQuerterFormatter(dateCondition.fixDate)
      }
  }
  // // 对比项的时间配置
  if (compareTimerConfig.fixDate && 
      compareTimerConfig.dateMode === 'FIXDATE'
     ) {
      if (compareTimerConfig.timeUnit === 'WEEK') {
        compareTimerConfig.fixDate = getYearWeek(new Date(compareTimerConfig.fixDate))
      }
      
      if (compareTimerConfig.timeUnit === 'QUARTER') {
          compareTimerConfig.fixDate = getQuerterFormatter(compareTimerConfig.fixDate)
      }
  }  
  emit('reviewResultData', reviewResultParams);
};

const timeUnit = ref()
const handleChangeDateMode = (v: any) => {
  indexConfig.dateCondition.offset = 1;
  indexConfig.dateCondition.fixDate = '';
};

watch(
  () => props.metricsConfig,
  (val) => {
    if (val) {
      Object.keys(val).forEach(key => {
          indexConfig[key] = val[key]
        })
      const dateCondition = indexConfig.dateCondition
        const compareTimerConfig = indexConfig.compare.dateCondition
        // 默认数据时间的配置
        if ( dateCondition.dateMode === 'FIXDATE') {
            if (dateCondition.timeUnit === 'WEEK') {
              let start = dateCondition.fixDate.split("-");
              if (start.length == 2) {
                dateCondition.fixDate = getDateOfWeek(start[1], start[0]);
              }
              
            }
            if (dateCondition.timeUnit === 'QUARTER') {
              if (dateCondition.fixDate.indexOf('Q') > -1) {
                dateCondition.fixDate = showQuerterFormatter(dateCondition.fixDate)
              }
            }
        }
        // 对比项的时间配置
        if (compareTimerConfig.fixDate && 
            compareTimerConfig.dateMode === 'FIXDATE') {
            if (compareTimerConfig.timeUnit === 'WEEK') {
              let fixDate = compareTimerConfig.fixDate.split("-");
              if (fixDate.length == 2) {
                compareTimerConfig.fixDate = getDateOfWeek(fixDate[1], fixDate[0]);
              }
            }
            if (compareTimerConfig.timeUnit === 'QUARTER') {
              if (compareTimerConfig.fixDate.indexOf('Q') > -1) {
                compareTimerConfig.fixDate = showQuerterFormatter(compareTimerConfig.fixDate)
              }
                
            }
        }  
      getFilterDimension(val.metricsId)
    } else {
      Object.keys(defaultMetricConfig).forEach(key => {
        indexConfig[key] = defaultMetricConfig[key]
      })
    }
    timeUnit.value = indexConfig.dateCondition.timeUnit; // 提供给右侧默认时间

    // todo: 提供给对比项时间使其保持时间粒度一样哦
    indexConfig.compare.dateCondition.timeUnit = indexConfig.dateCondition.timeUnit 
  },
  {
    immediate: true
  }
);
</script>

<template>
  <div class="index-card-config">
    <div>
      <span class="label-name">名称</span>
      <a-input
        v-model="indexConfig.cardName"
        placeholder="请输入"
        :max-length="20"
        show-word-limit
        size="small"
      />
    </div>
    <div>
      <div class="dis-flex space-between mb-4 align-item">
        <span class="label-name">指标</span>
        <a-popover
          position="lt"
          trigger="click"
          :content-style="{ width: '210px', padding: '0' }"
          v-model="indexPopoverVisible"
          content-class="change-card-content"
        >
          <icon-swap
            class="exchangeIcon"
            @click="
              () => {
                indexPopoverVisible = true;
              }
            "
          />
          <template #content>
            <index-tree-list
              :groupId="undefined"
              @handleIndex="(v:any) => {
                  changeIndexCard(v)
              }"
            ></index-tree-list>
          </template>
        </a-popover>
      </div>
      <div class="index-name-title">
        <div class="title-input">
          <span class="title-input-value">{{ indexConfig.metricsName }}</span>
          <span>
            <img
              :src="settingImg"
              class="title-input-editIcon"
              @click="handlePopModal"
            />
          </span>
        </div>
      </div>
    </div>

    <div>
      <span class="label-name">默认数据时间</span>
      <div class="data-time dis-flex">
        <TimeSelect
          :styleWidth="styleWidth"
          v-model="indexConfig"
          :timeTypeoption="DATEMODE"
          @handleChangeDateMode="handleChangeDateMode"
          size="small"
        />
      </div>
    </div>
    <div>
      <span class="label-name">目标值</span>
      <a-input-number
        v-model="indexConfig.target"
        :precision="0"
        placeholder="请输入"
        :min="1"
        size="small"
      />
    </div>
    <div>
      <div class="dis-flex space-between align-item">
        <span class="label-name">指标对比</span>
        <img
          :src="indexAdd"
          alt=""
          :class="[{disabledClick: indexConfig?.compare?.compareName}]"
          :style="{ width: '14px', height: '14px' }"
          @click="handleIndexCompare('add')"
        />
      </div>
      <div v-if="indexConfig?.compare?.compareName">
        <div class="index-compare-input" @click="handleIndexCompare('edit')">
          <a-input
            v-model="indexConfig.compare.compareName"
            readonly
            size="small"
          >
            <template #suffix>
              <icon-delete @click="(e:any) => {
                e.preventDefault();
                e.stopPropagation();
                indexConfig.compare = defaultMetricConfig.compare
              }"/>
            </template>
          </a-input>
        </div>
      </div>
    </div>
    <div class="preview-btn">
      <a-button type="outline" size="small" @click="metricsPreview"
        >确定</a-button
      >
    </div>
  </div>

  <index-modal
    ref="indexModalRef"
    :metricsName="indexConfig.metricsName"
    :metricsId="indexConfig.metricsId"
    :dimensionConditionObj="dimensionConditionObj"
    :curMetricsSetting="indexConfig.metricsSetting"
    @timeConfigSuccess="timeConfigSuccess"
  ></index-modal>
  <index-compare-modal
    :index-compare="indexConfig.compare"
    ref="indexCompareRef"
    @indexConfigSuccess="indexCompareOk"
  ></index-compare-modal>
</template>

<style lang="scss" scoped>
@import './index.scss';
</style>
